//
//  AppDelegate.m
//  GongXinDangJian
//
//  Created by apple on 17/11/29.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "AppDelegate.h"
#import "ZJTabBarViewController.h"
#import "XLSlideMenu.h"
#import "LPLeftViewController.h"
#import "AppUpdateViewController.h"
#import "LoginViewController.h"
#import "ZJLoginJudgeManager.h"
#import "PolyvSettings.h"
#import "PolyvUtil.h"
#import "JPUSHService.h"
#import <UMCommon/UMCommon.h>           // 公共组件是所有友盟产品的基础组件，必选
#import <UMAnalytics/MobClick.h>        // 统计组件

//极光推送
#define PUSHID @"fe81c781601ae0e00c1e5c1e"//工信党建

@interface AppDelegate ()<AppUpdateViewControllerDelegate , JPUSHRegisterDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
//    [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:@"isLogin"];
//    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"isLogin"];
    [self initPolyvSettings];
    [self initUMSocialStatistics];
    [self initJPushWithOptions:launchOptions];
    // 播放器即将播放通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(videoStarted:) name:@"UIMoviePlayerControllerDidEnterFullscreenNotification" object:nil];
    // 播放器即将退出通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(videoFinished:) name:@"UIMoviePlayerControllerDidExitFullscreenNotification" object:nil];
    
    AppUpdateViewController *vc = [AppUpdateViewController new];
    UINavigationController * mainNav = [[UINavigationController alloc]initWithRootViewController:vc];
    mainNav.navigationBar.hidden = YES;
    vc.delegate = self;
    self.window.rootViewController = mainNav;
    [self.window makeKeyAndVisible];
    /**  修改状态栏字体颜色  */
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    return YES;
}


#pragma mark - 友盟统计
- (void)initUMSocialStatistics{
    [UMConfigure initWithAppkey:@"5ab1c41df29d9821ef00005d" channel:nil];
    [MobClick setScenarioType:E_UM_NORMAL];
}


#pragma mark - 极光推送
- (void)initJPushWithOptions:(NSDictionary *)launchOptions{
    // Required
    // notice: 3.0.0及以后版本注册可以这样写,也可以继续 旧的注册 式
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        // 可以添加 定义categories
        // NSSet<UNNotificationCategory *> *categories for iOS10 or later
        // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    
    
    //    NSString *advertisingId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    
    // Required
    // init Push
    // notice: 2.1.5版本的SDK新增的注册方法，改成可上报IDFA，如果没有使用IDFA直接传nil
    // 如需继续使用pushConfig.plist文件声明appKey等配置内容，请依旧使用[JPUSHService setupWithOption:launchOptions]方式初始化。
    [JPUSHService setupWithOption:launchOptions appKey:PUSHID
                          channel:@""
                 apsForProduction:YES];
    
    
    //接受自定义消息
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self selector:@selector(networkDidReceiveMessage:) name:kJPFNetworkDidReceiveMessageNotification object:nil];
}

/**
 自定义消息
 
 @param notification 通知
 */
- (void)networkDidReceiveMessage:(NSNotification *)notification {
    NSDictionary * userInfo = [notification userInfo];
    
    //    NSString *content = [userInfo valueForKey:@"content"];
    //附加属性
    NSDictionary *extras = [userInfo valueForKey:@"extras"];
    if ([extras[@"event_type"] integerValue] == 1) {
        if (![extras[@"SYS_MAC"] isEqualToString:[ToolClass getMacAddress]]) {
            [self logoutWithMsg:[userInfo valueForKey:@"content"]];
        }
    }
}


-(void)logoutWithMsg:(NSString *)msg{
    if (msg.length == 0) {
        msg = @"";
    }
    /**  这是退出登录  */
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"isLogin"];
    //停止接受推送
    [JPUSHService setTags:[NSSet set] alias:@"" callbackSelector:nil object:nil];
    
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"YBHomeRequestTime"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:USER_INFO];
    [ZJUserInfoModel updateUserInfoFormNSUserDefaults];
    UIAlertController * alertVC = [UIAlertController alertControllerWithTitle:@"系统消息" message:msg preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction * action = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:[LoginViewController new]];
        UIWindow * window =  [[UIApplication sharedApplication].delegate window];
        window.rootViewController = nav;
    }];
    [alertVC addAction:action];
    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertVC animated:YES completion:^{
        
    }];
}

- (void)AppUpdateViewControllerDeleGate_show{
    
    [self changeWindowRootController];
}


-(void)changeWindowRootController{
    UIViewController *rootViewController;
    if (![[NSUserDefaults standardUserDefaults] objectForKey:@"isLogin"]) {
        rootViewController = [LoginViewController new];
        UINavigationController * mainNav = [[UINavigationController alloc]initWithRootViewController:rootViewController];
        mainNav.navigationBar.hidden = YES;
        self.window.rootViewController = mainNav;
        [self.window makeKeyAndVisible];
    }else{
        /**  主控制器  */
        ZJTabBarViewController *zj = [[ZJTabBarViewController alloc] init];
        
        //右侧菜单
        LPLeftViewController *rightVC = [[LPLeftViewController alloc] init];
        //创建滑动菜单
        XLSlideMenu *slideMenu = [[XLSlideMenu alloc] initWithRootViewController:zj];
        slideMenu.rightViewController = rightVC;
        //设置根导航控制器
        UINavigationController * mainNav = [[UINavigationController alloc]initWithRootViewController:slideMenu];
        mainNav.navigationBar.hidden = YES;
        self.window.rootViewController = mainNav;
        [self.window makeKeyAndVisible];
        [self atuoLogin];
    }
    
}



#pragma mark - 自动登录获取最新信息

- (void)atuoLogin{
    if ([CManager zj_validateMobile: ZJUSERINFORMODEL.ORG_ACCOUNT.MOBILE]) {
        NSDictionary *dict = @{@"MOBILE":ZJUSERINFORMODEL.ORG_ACCOUNT.MOBILE,@"CODE_SOURCE":@"login"};
        //获取验证码
        __weak typeof(self) weakSelf = self;
        [NetWorkingManager postWithUrlString:[NetWorkingURL getMobileCode] Parameter:dict Success:^(id object) {
            NetWorkModel *model = [NetWorkModel yy_modelWithJSON:object];
            if ([model.STATE isEqualToString:@"30000"]) {
                [weakSelf loginInfoCode:[object objectForKey:@"CODE"]];
            }
        } Fail:^(id object) {
        }];
    }
}


- (void)loginInfoCode:(NSString *)code{
    if (ZJUSERINFORMODEL.ORG_ACCOUNT.MOBILE) {
        NSDictionary *dict = @{@"MOBILE":ZJUSERINFORMODEL.ORG_ACCOUNT.MOBILE,@"CODE_SOURCE":@"login",@"MOBILE_CODE":code};
        __weak typeof(self) weakSelf = self;
        [NetWorkingManager postWithUrlString:[NetWorkingURL login] Parameter:dict Success:^(id object) {
            [weakSelf judgeLoginSuccessWith:object];
        } Fail:^(id object) {
            
        }];
    }
    
    
}
/** 判断是否登录成功 */
- (void)judgeLoginSuccessWith:(NSDictionary *)object{
    NetWorkModel *model = [NetWorkModel yy_modelWithJSON:object];
    if ([model.STATE isEqualToString:@"30000"]) {//登录成功
        [[NSUserDefaults standardUserDefaults] setObject:[object yy_modelToJSONString] forKey:USER_INFO];
        [ZJUserInfoModel updateUserInfoFormNSUserDefaults];
        [ToolClass ybLoadRequestDataForCache];
    }
    else{
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"isLogin"];
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"YBHomeRequestTime"];
        [JPUSHService setTags:[NSSet set] alias:@"" callbackSelector:nil object:nil];
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:USER_INFO];
        [ZJUserInfoModel updateUserInfoFormNSUserDefaults];
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:[LoginViewController new]];
        self.window.rootViewController = nav;
    }
}


#pragma mark - 屏幕旋转
//AppDelegate.m
-  (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
    
    if(_isFull){
        return UIInterfaceOrientationMaskLandscape;
    }
    return UIInterfaceOrientationMaskPortrait;
}
- (void)videoStarted:(NSNotification *)sender{
    
    self.isFull = YES;
}
- (void)videoFinished:(NSNotification *)sender{
    
    self.isFull = NO;
}


#pragma mark - 保利威视（视频）
- (void)initPolyvSettings{
    
    // 配置下载目录
    [PolyvSettings.sharedInstance setDownloadDir:[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/plvideo/a"]];
    // 配置日志等级
    [PolyvSettings.sharedInstance setLogLevel:PLVLogLevelAll];
    // 开启 HttpDNS 功能
    [PolyvSettings.sharedInstance setHttpDNSEnable:YES];
    
    // 配置sdk加密串
    // NSString *appKey = @"你的SDK加密串";
    NSString *appKey = @"Cq5RRhkjoK5IhucEAlCcq2xKA7yIguTAg2g0LRXWdnEcp5hTYrsKFrls8XsFMoKsnYzRcu4292JjLVw7AIFyOdlkiN9sa6lCFECxdHHrv58TmRJvgOF7PDYXUq03WNyxeVQWCrsk3WMTwFUSWSFJNA==";
    // 使用默认加密秘钥和加密向量解密 SDK加密串
    NSArray *config = [PolyvUtil decryptUserConfig:[appKey dataUsingEncoding:NSUTF8StringEncoding] key:@"VXtlHmwfS2oYm0CZ" iv:@"2u9gDPKdX6GyQJKU"];
    
    [[PolyvSettings sharedInstance] initVideoSettings:[config objectAtIndex:1] Readtoken:[config objectAtIndex:2] Writetoken:[config objectAtIndex:3] UserId:[config objectAtIndex:0]];
    
    // 配置sdk加密串示例(使用网络接口)
    
}


- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    /// Required - 注册 DeviceToken
    NSMutableString *deviceTokenString1 = [NSMutableString string];
    const char *bytes = deviceToken.bytes;
    NSUInteger iCount = deviceToken.length;
    for (int i = 0; i < iCount; i++) {
        [deviceTokenString1 appendFormat:@"%02x", bytes[i]&0x000000FF];
    }
    [[NSUserDefaults standardUserDefaults] setObject:deviceTokenString1 forKey:@"deviceToken"];
    [JPUSHService registerDeviceToken:deviceToken];
}


-(void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler
{
    
}


-(void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler
{
    
}



- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


@end
